﻿using System;
using System.Collections.Generic;

namespace ProblemsSet
{
    public class Problem_141 : BaseProblem
    {
        public override object GetResult()
        {
            const long max = 1000000000000;

            ulong sum = 0;

            var mxn = Math.Sqrt(max);

            var hs = new HashSet<long>();

            for (long n = 1; n <mxn; n++)
            {
                var mxd = Math.Sqrt(max/(double)n);
                for (long d = 1; d < mxd; d++)
                {
                    var mxc = Math.Pow((max/(double)(d*n)-d)/(double)n,1/(double)3);
                    for (long c = d; c <= mxc; c++)
                    {
                        long rN = n*d*(c*c*c*n + d);
                        if (rN >= max || rN <=0)
                            break;
                        if (hs.Contains(rN))
                            continue;
                        if (!MathLogic.IsSquare2(rN))
                            continue;
                        if (MathLogic.GetNOD(c,d) != 1)
                            continue;
                        hs.Add(rN);
                        sum += (ulong) rN;
                    }
                }
            }
            return sum;
        }

        public override string Problem
        {
            get
            {
                return @"A positive integer, n, is divided by d and the quotient and remainder are q and r respectively. In addition d, q, and r are consecutive positive integer terms in a geometric sequence, but not necessarily in that order.

For example, 58 divided by 6 has quotient 9 and remainder 4. It can also be seen that 4, 6, 9 are consecutive terms in a geometric sequence (common ratio 3/2).
We will call such numbers, n, progressive.

Some progressive numbers, such as 9 and 10404 = 1022, happen to also be perfect squares.
The sum of all progressive perfect squares below one hundred thousand is 124657.

Find the sum of all progressive perfect squares below one trillion (1012).";
            }
        }

        public override bool IsSolved
        {
            get
            {
                return true;
            }
        }

        public override object Answer
        {
            get
            {
                return 878454337159;
            }
        }
    }
}
